import * as echarts from '../../ec-canvas/echarts';
const app = getApp()
const utils = require('../../utils/util.js')
function setOption(chart, options) {
  const option = {
    title: {
      left: 24,
      text: '温度监控图',
      textStyle: {
        color: '#333333',
        fontSize: 14
      },
      subtext: '温度（单位℃）',
      subtextStyle: {
        color: '#666666',
        fontSize: 11
      }
    },
    color: ["#ffe064", "#8A0808", "#00ff00"],
    legend: {
      right: 24,
      data: options.legend
    },
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        let str = '', l = params.length, lk1 = l - 1;
        for(var i=0;i < l; i++) {
          let splitx = params[i].data[0].split(" ");
          str = str + (params[i].seriesName + splitx[1] + ' ' +  params[i].data[1] + "℃");
          if (i < lk1 ) {
            str = str + '\n' ;
          }
        }
        return str;
      },
      axisPointer: {
        animation: false
      }
    },
    xAxis: {
      type: 'time',
      boundaryGap: false,
      axisTick: {
        show: false
      },
    },
    yAxis: {
      show: false
    },
    series: options.series,
    dataZoom: [
      {
        type: 'slider',
        show: false,//show属性为false不展示缩放手柄，为true展示缩放手柄
        start: 0,
        end: 45,
        // handleSize: 88  该属性是缩放手柄的宽度
      },
      {
        type: 'inside',
        start: 0,
        end: 45
      }
    ]
  };
  chart.setOption(option);
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    skin: '',
    no: '', // 设备号
    barnName: '',
    zoneName: '',
    devName : '',
    lastTime: '',
    lastTemp: '-',
    ec: {
      lazyLoad: true
    },
    isDisposed: false,
    deviceId : 0
  },

  toPageWarn() {
    wx.navigateTo({
      url: '/pages/record/warn',
    })
  },

  toPageTemp() {
    let jumpUrl = '/pages/record/temp?deviceId=' + this.data.deviceId +
      "&dceNo=" + this.data.no + 
      "&barnName=" + this.data.barnName +
      "&zoneName=" + this.data.zoneName + 
      "&devName=" + this.data.devName;
    wx.navigateTo({
      url: jumpUrl,
    })
  },

  toWateLevel() {
    let jumpUrl = '/pages/record/shuiwei?deviceId=' + this.data.deviceId +
      "&dceNo=" + this.data.no + 
      "&barnName=" + this.data.barnName +
      "&zoneName=" + this.data.zoneName +
      "&devName=" + this.data.devName;
    wx.navigateTo({
      url: jumpUrl,
    })
    /*let jumpUrl = '/pages/record/waterLevel?deviceId=' + this.data.deviceId +
      "&dceNo=" + this.data.no + 
      "&barnName=" + this.data.barnName +
      "&zoneName=" + this.data.zoneName + 
      "&devName=" + this.data.devName;
    wx.navigateTo({
      url: jumpUrl,
    })*/
  },

  initChart: function (series) {
    this.ecComponent.init((canvas, width, height, dpr) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });

      const legend = ['今天', '昨天', '前天']
      setOption(chart, {
        legend,
        series
      });
      // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
      this.chart = chart;
      this.setData({
        isDisposed: false
      });
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return chart;
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    this.ecComponent = this.selectComponent('#mychart-dom-line')
    this.setData({
      deviceId: options.deviceId || 0
    });
    this.initHeadData();

    app.setNavBar()
    const { skin } = app.globalData
    this.setData({
      skin
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  

  },
  initHeadData : function() {
    let that = this;
    let p1 = utils.promiseGet('/wx/property/getDeviceInfoById', {"deviceId" : this.data.deviceId}),
        p2 = utils.promiseGet('/wx/device/waterchannel/getLeastDataByDeviceId', {"deviceId" : this.data.deviceId}),
        p3 = utils.promiseGet('/wx/device/waterchannel/calLeastThreeData', {"deviceId" : this.data.deviceId});
    Promise.all([p1, p2, p3]).then((result) => {
      //p1
      if (result && result[0] && result[0].code == 200) {
        let deviceInfo = result[0].data || {};
        that.setData({
          barnName : deviceInfo.oxtName || '',
          zoneName : deviceInfo.oxtAreaName || '',
          no : deviceInfo.dceNo || '',
          devName : deviceInfo.name || ''
        });
      }
      //p2
      if (result && result[1] && result[1].code == 200) {
        let leastData = result[1].data || {};
        that.setData({
          lastTime : leastData.createTime || '',
          lastTemp : leastData.temperature || '-',
        });
      }
      //p3
      if (result && result[2] && result[2].code == 200) {
        let chartData = result[2].data || {};
        var mySeries = new Array();
        //今天
        let ymd = '';
        if (chartData.today && chartData.today.length > 0) {
          var todayArr = [];
          for (var i = 0; i < chartData.today.length; i++) {
            if (ymd == '') {
              var splitStr = chartData.today[i].createTime.split(' ');
              ymd = splitStr[0];
            }
            var item = new Array(chartData.today[i].createTime, chartData.today[i].temperature);
            todayArr.push(item);
          }
          let todayData = {
            name: '今天',
            data: todayArr,
            type: 'line',
            showSymbol: false,
            hoverAnimation: false,
          };
          mySeries.push(todayData);
        }
        //昨天
        if (chartData.yesterday && chartData.yesterday.length > 0) {
          var yesterdayArr = [];
          for (var i = 0; i < chartData.yesterday.length; i++) {
            var splitStr1 = chartData.yesterday[i].createTime.split(' ');
            var item = new Array(ymd + " " + splitStr1[1], chartData.yesterday[i].temperature);
            yesterdayArr.push(item);
          }
          let yesterdayData = {
            name: '昨天',
            data: yesterdayArr,
            type: 'line',
            showSymbol: false,
            hoverAnimation: false,
          };
          mySeries.push(yesterdayData);
        }
        //前天
        if (chartData.yesterdayAgo && chartData.yesterdayAgo.length > 0) {
          var yesterdayAgoArr = [];
          for (var i = 0; i < chartData.yesterdayAgo.length; i++) {
            var splitStr2 = chartData.yesterdayAgo[i].createTime.split(' ');
            var item = new Array(ymd + " " +splitStr2[1], chartData.yesterdayAgo[i].temperature);
            yesterdayAgoArr.push(item);
          }
          let yesterdayAgoData = {
            name: '前天',
            data: yesterdayAgoArr,
            type: 'line',
            showSymbol: false,
            hoverAnimation: false,
          };
          mySeries.push(yesterdayAgoData);
        }

        let anchor = [
            [ymd + " 00:00:00", 0],
            [ymd + " 23:59:59", 0]
        ];
        let anchorData = {
            type : 'line',
            name: '.anchor',
            data: anchor,
            showSymbol:false, 
            itemStyle:{normal:{opacity:0}},
            lineStyle:{normal:{opacity:0}}
        };
        mySeries.push(anchorData);
        console.log(mySeries);
        that.initChart(mySeries);
      }
    }).catch(function(e){
        console.log(e);
    });
  }
})